package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-22
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public ApBehaviorEntry getEntry(EntryDto entryDto) {

        if (entryDto.getUserId() != null) {

            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();

            query.eq(ApBehaviorEntry::getEntryId, entryDto.getUserId().toString());

            query.eq(ApBehaviorEntry::getType, 1);

            ApBehaviorEntry one = this.getOne(query);

            if (one != null) {

                return one;
            } else {

                one = new ApBehaviorEntry();

                one.setCreatedTime(new Date());

                one.setType(1);

                one.setEntryId(entryDto.getUserId().toString());

                this.save(one);

                return one;
            }
        }
        if (entryDto.getEquipmentId() != null) {

            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();

            query.eq(ApBehaviorEntry::getEntryId, entryDto.getEquipmentId()).eq(ApBehaviorEntry::getType, 0);

            ApBehaviorEntry one = this.getOne(query);

            if (one != null) {

                return one;
            } else {

                one = new ApBehaviorEntry();

                one.setEntryId(entryDto.getEquipmentId());

                one.setType(0);

                one.setCreatedTime(new Date());

                this.save(one);

                return one;
            }
        }
        return null;
    }
}
